package com.uinnova.product.eam.web.diagram.peer.impl;

import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.comm.model.CVcDiagram;
import com.uinnova.product.eam.comm.model.CVcDiagramDir;
import com.uinnova.product.eam.comm.model.VcDiagram;
import com.uinnova.product.eam.comm.model.VcDiagramDir;
import com.uinnova.product.eam.model.VcDiagramDirInfo;
import com.uinnova.product.eam.model.VcDiagramInfo;
import com.uinnova.product.eam.service.VcDiagramSvc;
import com.uinnova.product.eam.web.diagram.bean.DiagramDirInfo;
import com.uinnova.product.eam.web.diagram.peer.DiagramPeer;
import com.uinnova.product.eam.web.integration.bean.DiagramAuth;
import com.uinnova.product.eam.web.util.DmvFileUtil;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.util.sys.SysUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

public class DiagramPeerImpl implements DiagramPeer {
	private static Logger logger = LoggerFactory.getLogger(DiagramPeerImpl.class);

	@Value("${http.resource.space}")
	private String httpResouceUrl;

	@Autowired
	private VcDiagramSvc diagramSvc;

	@Autowired
	private IUserApiSvc userApiSvc;

	@Autowired
	private DmvFileUtil dmvFileUtil;

	/** RSM-SLAVE访问入口 **/
	private String rsmSlaveRoot;

	/** RSM分类代码 **/
	private String rsmClassCode;

	public String getRsmSlaveRoot() {
		return rsmSlaveRoot;
	}

	public void setRsmSlaveRoot(String rsmSlaveRoot) {
		this.rsmSlaveRoot = rsmSlaveRoot;
	}

	public String getRsmClassCode() {
		return rsmClassCode;
	}

	public void setRsmClassCode(String rsmClassCode) {
		this.rsmClassCode = rsmClassCode;
	}


	@Override
	public VcDiagramDir queryDirById(Long id) {
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		id = id == null ? 0 : id;
		VcDiagramDir diagramDir = diagramSvc.queryDiagramDirById(domainId, id);
		subDirCreatorAndModifier(diagramDir);
		return diagramDir;
	}

	/**
	 * 修整视图信息
	 *
	 * @param diagramInfo
	 * @param token
	 */
	private void trimDiagram(VcDiagramInfo diagramInfo, String token) {
		if (diagramInfo == null)
			return;
		fillRsmResource(diagramInfo, token);

		fillPath(diagramInfo);
		subCreatorAndModifier(diagramInfo);

	}

	/**
	 * 将创建者和修改者名字剪切掉 aa[bb] --> aa
	 *
	 * @param diagramInfo
	 *            视图信息
	 */
	private void subCreatorAndModifier(VcDiagramInfo diagramInfo) {
		if (diagramInfo != null) {
			VcDiagram diagram = diagramInfo.getDiagram();
			if (diagram != null) {
				diagram.setCreator(subName(diagram.getCreator()));
				diagram.setModifier(subName(diagram.getModifier()));
			}
		}
	}

	private String subName(String name) {
		if (name != null) {
			int lastIndexOf = name.lastIndexOf("[");
			if (lastIndexOf > 0) {
				return name.substring(0, lastIndexOf);
			}
		}
		return name;
	}

	/**
	 * 填充视图的远程资源信息
	 *
	 * @param diagramInfo
	 * @param token
	 */
	private void fillRsmResource(VcDiagramInfo diagramInfo, String token) {
		if (diagramInfo == null)
			return;

		VcDiagram diagram = diagramInfo.getDiagram();
		if (diagram == null)
			return;

		String diagramJsonPath = diagram.getDiagramJson();

		if (diagramJsonPath != null && diagramJsonPath.startsWith(httpResouceUrl)) {
			diagramJsonPath = diagramJsonPath.substring(httpResouceUrl.length());
		}

		if (diagramJsonPath != null) {
			try {
				String json = dmvFileUtil.getResourceContent(diagramJsonPath);
				diagramInfo.setJson(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void fillPath(VcDiagramInfo diagramInfo) {
		if (diagramInfo == null)
			return;
		VcDiagram diagram = diagramInfo.getDiagram();
		if (diagram == null)
			return;

		// 缩略图
		String icon1 = diagram.getIcon1();
		if (icon1 != null && !icon1.startsWith(httpResouceUrl)) {
			icon1 = httpResouceUrl + icon1;
			diagram.setIcon1(icon1);
		}

		String diagramBgImg = diagram.getDiagramBgImg();
		if (diagramBgImg != null && !BinaryUtils.isEmpty(diagramBgImg.trim())
				&& !diagramBgImg.startsWith(httpResouceUrl)) {
			diagramBgImg = httpResouceUrl + diagramBgImg;
			diagram.setDiagramBgImg(diagramBgImg);
		}

		// 修整用户头像信息
		SysUser creator = diagramInfo.getCreator();
		if (creator != null) {
			String icon = creator.getIcon();
			// 这儿判断是因为当前用户是同一个对象，所以再修改会无限拼接，勿删！！！！！！
			if (icon != null && !icon.startsWith(this.httpResouceUrl)) {
				creator.setIcon(httpResouceUrl + icon);
			}
		}
	}

	private Map<Long, Integer> queryDirDiagramCount(Long domainId, Long[] dirIds, Long userId) {
		Map<Long, Integer> map = new HashMap<Long, Integer>();
		List<VcDiagramDirInfo> list = diagramSvc.queryDirDiagramCountList(domainId, dirIds, userId);
		if (BinaryUtils.isEmpty(list))
			return map;

		for (VcDiagramDirInfo dirInfo : list) {
			map.put(dirInfo.getDirId(), dirInfo.getDiagramCount() == null ? 0 : dirInfo.getDiagramCount());
		}
		return map;
	}

	private List<VcDiagramDir> queryAndFillDiagramDirList(Long domainId, Long pId, String like, Long userId, Integer dataStatus,String order) {
		CVcDiagramDir cdt = new CVcDiagramDir();
		cdt.setParentId(pId);
		cdt.setUserId(userId);
		cdt.setDataStatus(dataStatus);
		if (like != null) {
			cdt.setDirName(like);
		}
		cdt.setDomainId(domainId);
		cdt.setDirType(1);
		List<VcDiagramDir> queryDiagramDirList = diagramSvc.queryDiagramDirList(domainId, cdt, order);

		subListDirCreatorAndModifier(queryDiagramDirList);
		return queryDiagramDirList;
	}

	private void subListDirCreatorAndModifier(List<VcDiagramDir> diagramDirs) {
		if (diagramDirs != null) {
			for (VcDiagramDir diagramDir : diagramDirs) {
				subDirCreatorAndModifier(diagramDir);
			}
		}
	}

	@Override
	public void addDirageAuth(DiagramDirInfo info) {
		if (info != null && info.getDiagramInfoPage() != null && info.getDiagramInfoPage().getData() != null
				&& info.getDiagramInfoPage().getData().size() > 0) {
			List<VcDiagramInfo> diagrams = info.getDiagramInfoPage().getData();
			Set<Long> diagramIds = new HashSet<>();
			for (VcDiagramInfo diagram : diagrams) {
				diagramIds.add(diagram.getDiagram().getId());
			}
			Map<Long, DiagramAuth> diagramAuthMap = getDiagramAuth(diagramIds);
			for (VcDiagramInfo diagram : diagrams) {
				Long diagramId = diagram.getDiagram().getId();
				if (diagramAuthMap.get(diagramId) != null) {
					DiagramAuth auth = diagramAuthMap.get(diagramId);
					diagram.setSeeAuth(auth.isSee());
					diagram.setEditAuth(auth.isEdit());
				}
			}
		}

	}


	public Map<Long, DiagramAuth> getDiagramAuth(Collection<Long> diagramIds) {
		if (CollectionUtils.isEmpty(diagramIds)) {
			return new HashMap<>();
		}
		Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
		Map<Long, DiagramAuth> diagramAuthMap = new HashMap<>();
		Long userId = SysUtil.getCurrentUserInfo().getId();

		// 默认权限 走小组权限
		CVcDiagram diagramquery = new CVcDiagram();
		diagramquery.setIds(diagramIds.toArray(new Long[diagramIds.size()]));
		List<VcDiagram> diagrams = diagramSvc.queryDiagramList(1L, diagramquery, null);
		// 广场的图特殊处理，在广场全部赋予查看权限至少
		Set<Long> openDiagramIds = new HashSet<>();
		Map<Long, DiagramAuth> diagramAuthTemp = new HashMap<>();
		for (VcDiagram diagram : diagrams) {
			diagramAuthTemp.put(diagram.getId(), new DiagramAuth());
			// 不再通过creator字段判断是否为创建者，通过视图的userid
			if (diagram.getUserId().longValue() == userId.longValue()) {
				diagramAuthTemp.get(diagram.getId()).setEdit(true);
				diagramAuthTemp.get(diagram.getId()).setSee(true);
			}
			// if(diagram.getCreator().equals(userCode)){
			// diagramAuthTemp.get(diagram.getId()).setEdit(true);
			// diagramAuthTemp.get(diagram.getId()).setSee(true);
			// }
			if (diagram.getIsOpen() == 1) {
				openDiagramIds.add(diagram.getId());
			}
		}

		// 组装权限
		for (Long diagramId : diagramIds) {
			DiagramAuth auth = new DiagramAuth();
			if (diagramAuthTemp.containsKey(diagramId) && diagramAuthTemp.get(diagramId).isSee()
					&& diagramAuthTemp.get(diagramId).isEdit()) {
				// 代表当前登陆用户是这些视图所有者拥有所有权限
				auth.setSee(true);
				auth.setEdit(true);
			}
			diagramAuthMap.put(diagramId, auth);
		}
		// 开始特殊处理广场视图
		if (openDiagramIds != null && openDiagramIds.size() > 0) {
			for (Long diagramId : openDiagramIds) {
				diagramAuthMap.get(diagramId).setSee(true);
			}
		}


		return diagramAuthMap;
	}


	private void subDirCreatorAndModifier(VcDiagramDir diagramDir) {
		if (diagramDir != null) {
			diagramDir.setCreator(subName(diagramDir.getCreator()));
			diagramDir.setModifier(subName(diagramDir.getModifier()));
		}
	}

}
